/**
 * Created by KY on 2017/6/22.
 */
define('comps/session',['comps/ajax','ldfw/ldlibs/base64','crypto-js/index'],function(ajax,Base64,CryptoJS){
    let session = window.sessionStorage,
        encrypKey = '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', //sh1 password
        jsonKey;
    function encrypt(message, encrypKey) {
        var encrypted = CryptoJS.DES.encrypt(message,encrypKey)
        return encrypted.toString();
    }
    function decrypt(message,encrypKey){
        var decrypted = CryptoJS.DES.decrypt(message,encrypKey)
        return decrypted.toString(CryptoJS.enc.Utf8)
    }
    return {
        setItem:function(key,value){
            key = Base64.encode(key)
            jsonKey = JSON.parse(session.getItem('jsonKey'))||[]
            if(typeof value=== typeof 'string'){
                value = encrypt(value,encrypKey)
                session.setItem(key,value)
                if(_.contains(jsonKey,key)){
                    jsonKey.splice(jsonKey.indexOf(key),1)
                }
            }else{
                value = encrypt(JSON.stringify(value),encrypKey)
                session.setItem(key,value)
                if(!_.contains(jsonKey,key)){
                    jsonKey.push(key)
                }
            }
            session.setItem('jsonKey',JSON.stringify(jsonKey))
        },
        getItem:function(key){
            key = Base64.encode(key)
            jsonKey = JSON.parse(session.getItem('jsonKey'))||[]
            if(session.getItem(key)){
                let value = decrypt(session.getItem(key),encrypKey)
                return jsonKey.indexOf(key)>-1?JSON.parse(value):value
            }
            return null
        },
        removeItem:function(key){
            session.removeItem(key)
        },
        clear:function(){
            session.clear()
        },
        getCurrentUser:function(){
            return this.getItem('cust_session')
        },
        setCurrentUser:function(user){
            this.setItem('cust_session',user)
        },
        flush:function(){
            const _this = this
            ajax.sync('get','currentCuster.do')
                .success(function(resp){
                    if(!resp.resultCode){
                        _this.setCurrentUser(_.omit(resp,'error_code','error_deal','error_info','error_level','error_prompt','row_id'))
                    }
                })
        }
    }
})